package com.rds.benchmark.operator;

import com.rds.benchmark.util.MakeValue;
import io.lettuce.core.api.sync.RedisCommands;
import io.lettuce.core.cluster.api.sync.RedisAdvancedClusterCommands;

import java.io.IOException;
import java.util.Date;

public class StableStringLettuceOperator extends TypeOperatorBase{

    private RedisAdvancedClusterCommands<String, String> clusterCommands;
    private RedisCommands<String, String> redisCommands;
    private String key;
    private static long ErrorTimestamp = 0;

    private final String value = MakeValue.value;

    private synchronized boolean needPrint() {
        long timestamp = System.currentTimeMillis() / 2000;
        if (timestamp != ErrorTimestamp) {
            ErrorTimestamp = timestamp;
            return true;
        }
        return false;
    }

    @Override
    public void init(Object conn, String key, int idx,String mode) {
        this.key = key;
        if(conn instanceof RedisAdvancedClusterCommands) {
            this.clusterCommands = (RedisAdvancedClusterCommands) conn;
            this.clusterCommands.set(key,value);
        } else if(conn instanceof RedisCommands){
            this.redisCommands = (RedisCommands) conn;
            this.redisCommands.set(key,value);
        }

    }

    @Override
    public Long clear() {
        Long del = 0L;
        if(redisCommands != null)
            del = redisCommands.del(key);
        else if(clusterCommands != null)
            del = clusterCommands.del(key);
        return del;
    }

    @Override
    public void operate() throws IOException {
        try {
            ++times;
            if(redisCommands != null)
                redisCommands.get(key);
            else if(clusterCommands != null)
                clusterCommands.get(key);
        } catch (Throwable t) {
            if (needPrint()) {
                System.out.println(new Date() + " ERROR: " + t.getMessage());
            }
        }
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
        }
    }
}
